#include "myopenglwidget.h"

unsigned int VBO,VAO;
unsigned int shaderProgram;
float vertices[]={
    -0.5f,-0.5f,0.0f,
    0.5f,-0.5f,0.0f,
    0.0f,0.5f,0.0f,
};

//顶点着色器
const char *vertexShaderSource="#version 330 core\n"
                                "layout (location=0) in vec3 aPos;\n"
                                "void main()\n"
                                "{\n"
                                " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
                                 "}\0";

//片段着色器
const char *fragmentShaderSource="#version 330 core\n"
                                 "out vec4 FragColor;\n"
                                 "void main()\n"
                                 "{\n"
                                 " FragColor = vec4(1.0f,0.5f,0.2f,1.0f);\n" "}\n\0";


MyOpenglWidget::MyOpenglWidget(QWidget *parent):QOpenGLWidget(parent) {


}

void MyOpenglWidget::initializeGL()
{
    this->initializeOpenGLFunctions();
    glGenVertexArrays(1,&VAO);
    glGenBuffers(1,&VBO);
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER,VBO);

    //将数据传入显存
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);

    //告知显卡如何解析
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(float),(GLvoid*)0);

    //开启VAO的属性
    glEnableVertexAttribArray(0);

    //解绑
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,0);

    //编译顶点着色器
    unsigned int vertexShader=glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader,1,&vertexShaderSource,NULL);
    glCompileShader(vertexShader);

    //编译片段着色器
    unsigned int fragmentShader=glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader,1,&fragmentShaderSource,NULL);
    glCompileShader(fragmentShader);


    //链接 link shaders
    shaderProgram=glCreateProgram();
    glAttachShader(shaderProgram,vertexShader);
    glAttachShader(shaderProgram,fragmentShader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
}

void MyOpenglWidget::resizeGL(int w, int h)
{

}

void MyOpenglWidget::paintGL()
{
    glClearColor(0.2f,0.3f,0.3f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shaderProgram);

    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES,0,3);

    //解绑
    glBindVertexArray(0);
}

